package main

import (
	"gateway-demo/core/application"
	"gateway-demo/core/config"
	"gateway-demo/core/http"
	rice "github.com/GeertJohan/go.rice"
	"github.com/joho/godotenv"
	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
	"os"
	"os/signal"
	"path/filepath"
	"syscall"
)

func main() {
	//version := internal.PrintableVersion()
	//version := "dev"
	// Catch signals from the OS requesting us to exit

	var err error
	var backendAssets *rice.Box
	backendAssets, err = rice.FindBox("backend-assets")
	log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
	zerolog.SetGlobalLevel(zerolog.InfoLevel)

	go func() {
		c := make(chan os.Signal, 1) // we need to reserve to buffer size 1, so the notifier are not blocked
		signal.Notify(c, os.Interrupt, syscall.SIGTERM)
		<-c
		os.Exit(1)
	}()

	// handle loading environment variabled from .env files
	envFiles := []string{".env", "gateway.env"}
	homeDir, err := os.UserHomeDir()
	if err == nil {
		envFiles = append(envFiles, filepath.Join(homeDir, "gateway.env"), filepath.Join(homeDir, ".config/gateway.env"))
	}
	envFiles = append(envFiles, "/etc/gateway.env")

	for _, envFile := range envFiles {
		if _, err := os.Stat(envFile); err == nil {
			log.Info().Str("envFile", envFile).Msg("env file found, loading environment variables from file")
			err = godotenv.Load(envFile)
			if err != nil {
				log.Error().Err(err).Str("envFile", envFile).Msg("failed to load environment variables from file")
				continue
			}
		}
	}

	//// Actually parse the CLI options
	//ctx := kong.Parse(&cli.CLI,
	//	kong.Description(
	//		`  ModelServices Gateway is a drop-in replacement OpenAI API for running LLM, GPT and genAI models locally on CPU, GPUs with consumer grade hardware.
	//
	//Some of the models compatible are:
	// - Vicuna
	// - Koala
	// - GPT4ALL
	// - GPT4ALL-J
	// - Cerebras
	// - Alpaca
	// - StableLM (ggml quantized)
	//
	//For a list of all available models for one-click install, check out: https://models.localai.io
	//
	//Copyright: Ettore Di Giacinto
	//
	//Version: ${version}
	//`,
	//	),
	//	kong.UsageOnError(),
	//	kong.Vars{
	//		"basepath": kong.ExpandPath("."),
	//		//"galleries": `[{"name":"localai", "url":"github:mudler/LocalAI/gallery/index.yaml@master"}]`,
	//		//"backends":  `[{"name":"localai", "url":"github:mudler/LocalAI/backend/index.yaml@master"}]`,
	//		"version": version,
	//	},
	//)
	//
	//// Configure the logging level before we run the application
	//// This is here to preserve the existing --debug flag functionality
	//logLevel := "info"
	//if cli.CLI.Debug && cli.CLI.LogLevel == nil {
	//	logLevel = "debug"
	//	zerolog.SetGlobalLevel(zerolog.DebugLevel)
	//	cli.CLI.LogLevel = &logLevel
	//}
	//
	//if cli.CLI.LogLevel == nil {
	//	cli.CLI.LogLevel = &logLevel
	//}
	//
	//switch *cli.CLI.LogLevel {
	//case "error":
	//	zerolog.SetGlobalLevel(zerolog.ErrorLevel)
	//	log.Info().Msg("Setting logging to error")
	//case "warn":
	//	zerolog.SetGlobalLevel(zerolog.WarnLevel)
	//	log.Info().Msg("Setting logging to warn")
	//case "info":
	//	zerolog.SetGlobalLevel(zerolog.InfoLevel)
	//	log.Info().Msg("Setting logging to info")
	//case "debug":
	//	zerolog.SetGlobalLevel(zerolog.DebugLevel)
	//	log.Debug().Msg("Setting logging to debug")
	//case "trace":
	//	zerolog.SetGlobalLevel(zerolog.TraceLevel)
	//	log.Trace().Msg("Setting logging to trace")
	//}
	//
	//// Populate the application with the embedded backend assets
	//cli.CLI.Context.BackendAssets = backendAssets
	//
	//// Run the thing!
	//err = ctx.Run(&cli.CLI.Context)
	//if err != nil {
	//	log.Fatal().Err(err).Msg("Error running the application")
	//}

	modelPath := os.Getenv("MODEL_PATH")
	machineTag := os.Getenv("MACHINE_TAG")
	backendsPath := os.Getenv("BACKENDS_PATH")
	appAddress := os.Getenv("APP_ADDRESS")
	opts := []config.AppOption{
		config.WithModelPath(modelPath),                // 模型路径
		config.WithBackendsPath(backendsPath),          // 后端路径
		config.WithBackendAssetsOutput("/tmp/backend"), // 临时后端资源目录
		config.WithThreads(2),                          // 线程数
		config.WithContextSize(2048),                   // 上下文大小
		config.WithUploadLimitMB(15),                   // 上传限制
		config.WithCors(true),                          // 开启 CORS
		config.WithDebug(false),                        // 关闭调试模式
		config.WithMachineTag(machineTag),
		config.WithBackendAssets(backendAssets),
		config.EnableSingleBackend,
		// 其他你需要的 AppOption 可以继续添加
	}

	app, err := application.New(opts...)
	if err != nil {

	}

	appHTTP, err := http.API(app)
	if err != nil {
		log.Error().Err(err).Msg("error during HTTP App construction")
	}

	appHTTP.Listen(appAddress)
}
